package com.ziyueyuwen.xiniao.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.DateUtil;
import com.suyeer.basic.util.EncryptUtil;
import com.suyeer.basic.util.HttpResUtil;
import com.suyeer.basic.util.LogUtil;
import com.suyeer.cache.RedisUtil;
import org.apache.commons.lang3.RandomUtils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.apache.commons.codec.CharEncoding.UTF_8;

/**
 * @author jun 2018/12/19.
 */
public class SmsUtil {
    private final static String ACCOUNT_SID = "99380286350b440bbe6ec3690528fa82";

    private final static String AUTH_TOKEN = "b032e8cb258942969a0676384881f42d";

    private final static String BASE_URL = "https://api.miaodiyun.com/20150822";

    private final static String OPERATION = "/industrySMS/sendSMS";

    private final static String SUCCESS_CODE = "00000";

    private final static String KEY_RESP_CODE = "respCode";

    public static void industrySMS(String phoneNum) throws Exception {
        String code = String.valueOf(RandomUtils.nextInt(100000, 999999));
        industrySMS(phoneNum, code);
    }

    public static void industrySMS(String phoneNum, String code) throws Exception {
        RedisUtil.ifCanSendCode(phoneNum, code);
        String tmpSmsContent = "【子曰语文】您的验证码为" + code + "，请于5分钟内正确输入，如非本人操作，请忽略此短信。";
        tmpSmsContent = URLEncoder.encode(tmpSmsContent, UTF_8);
        String url = BASE_URL + OPERATION;
        String body = String.format("accountSid=%s&to=%s&smsContent=%s%s", ACCOUNT_SID, phoneNum, tmpSmsContent, createCommonParam());
        JSONObject retObj = HttpResUtil.sendHttpPostRequest(url + "?" + body, new JSONObject());
        if (retObj == null || !SUCCESS_CODE.equals(retObj.getString(KEY_RESP_CODE))) {
            LogUtil.error(JSON.toJSONString(retObj));
            throw new Exception("发送验证码失败!");
        }
    }

    private static String createCommonParam() {
        // 时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        // 签名
        String sig = EncryptUtil.md5(ACCOUNT_SID + AUTH_TOKEN + timestamp).toLowerCase();
        return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType=json";
    }

    public static void main(String[] args) {
        try {
            System.err.println(DateUtil.getDateStr(new Date()));
            industrySMS("183542768600");
        } catch (Exception e) {
            LogUtil.error(e);
        }
    }
}
